﻿using System.Web.Mvc;
using TodoApp.Models;
using TodoApp.Repositories.Contract;
using TodoApp.ViewModels;

namespace TodoApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly IRepository<TodoItem> todoRepository;
        public HomeController(IRepository<TodoItem> todoRepository)
        {
            this.todoRepository = todoRepository;
        }
        public ActionResult Index()
        {
            int totalResults;
            var todoItems = todoRepository.Find(out totalResults, 1, 0);
            var viewModel = new TodoListViewModel
                {
                    TodoItems = todoItems
                };

            return View(viewModel);
        }

        public ActionResult Details(int id)
        {
            var todoItem = todoRepository.Get(id);

            return View(todoItem);
        }

        public ActionResult Edit(int id)
        {
            var todoItem = todoRepository.Get(id);
            var viewModel = new CreateTodoItemViewModel
            {
                TodoItem = todoItem
            };

            return View(viewModel);
        }

        public ActionResult Create()
        {
            var viewModel = new CreateTodoItemViewModel
                {
                    TodoItem = new TodoItem()
                };

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Edit(CreateTodoItemViewModel viewModel)
        {
            var todoItem = todoRepository.Get(viewModel.TodoItem.Id);
            todoItem.Name = viewModel.TodoItem.Name;
            todoItem.IsDone = viewModel.TodoItem.IsDone;
            todoItem.Priority = viewModel.TodoItem.Priority;

            return RedirectToAction("Details", new { id = todoItem.Id });
        }

        [HttpPost]
        public ActionResult Create(CreateTodoItemViewModel viewModel)
        {
            todoRepository.Add(viewModel.TodoItem);

            return RedirectToAction("Index");
        }

        public ActionResult Delete(int id)
        {
            var todoItem = todoRepository.Get(id);
            todoRepository.Delete(todoItem);

            return RedirectToAction("Index");
        }
    }
}
